<?php
 require_once '../../include.php';

// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-validate';

foreach ($_POST as $key => $value) {
	$value = urlencode(stripslashes($value));
	$req .= "&$key=$value";
}

// post back to PayPal system to validate
//将信息 POST 回给 PayPal 进行验证 
$header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " .strlen($req)."r\n\r\n";
$fp = fsockopen ('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30);

// assign posted variables to local variables
//将 POST 变量记录在本地变量中 
$item_name = $_POST['item_name'];
$item_number = $_POST['item_number'];

//$txn_id = $_POST['txn_id'];
$receiver_email = $_POST['receiver_email'];
//$payer_email = $_POST['payer_email'];

//判断回复 POST 是否创建成功 
if (!$fp) {
	// HTTP 错误 

}
else {
		

		//将回复 POST 信息写入 SOCKET 端口 
		fputs ($fp, $header . $req);
		//开始接受 PayPal 对回复 POST 信息的认证信息
		while (!feof($fp)) {
			$res = fgets ($fp, 1024);
			//已经通过认证 
			
			if (strcmp ($res, 'VERIFIED') == 0) { 
				//检查付款状态 
				//检查 txn_id 是否已经处理过 
				//检查 receiver_email 是否是您的 PayPal 账户中的 EMAIL 地址 
				//检查付款金额和货币单位是否正确 
				//处理这次付款，包括写数据库 
				mysql_query("update `stshop_order` set `Status` =1 WHERE `code` ='$item_number'");
			}
			else if (strcmp ($res, 'INVALID') == 0) {
				// log for manual investigation
				// 验证失败，可以不处理。

			}
		}
		fclose ($fp);
}
?>